#include "WorkoutDataHandler.h"
#include "nlohmann/json.hpp"  // 使用 nlohmann/json 库
#include <iostream>
#include <string>
#include <sstream>

#include <android/log.h>  // 添加 Android 日志头文件

#define LOG_TAG "WORKOUT_DATA_HANDLER"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)


using json = nlohmann::json;

// 构造函数私有化，确保只能通过 getInstance() 调用
WorkoutDataHandler::WorkoutDataHandler() {
    // 可以在这里进行一些初始化操作
}

void WorkoutDataHandler::parseJsonToWorkoutData(const std::string &jsonStr) {
    try {
        // 解析 JSON 字符串
        json jsonData = json::parse(jsonStr);

        // 根据proto文件的属性顺序给workoutData实例赋值
        if (jsonData.contains("instantaneousCadence")) {
            workoutData.add_spm(std::stof(jsonData["instantaneousCadence"].get<std::string>()));
        }
        if (jsonData.contains("instantaneousSpeed")) {
            workoutData.add_speed(std::stof(jsonData["instantaneousSpeed"].get<std::string>()));
        }
        if (jsonData.contains("instantaneousPower")) {
            workoutData.add_watts(std::stof(jsonData["instantaneousPower"].get<std::string>()));
        }
        if (jsonData.contains("avgCadence")) {
            workoutData.set_avgspm(std::stof(jsonData["avgCadence"].get<std::string>()));
        }
        if (jsonData.contains("distanceInSecond")) {
            workoutData.add_meters(std::stof(jsonData["distanceInSecond"].get<std::string>()));
        }
        if (jsonData.contains("avgPower")) {
            workoutData.set_avgwatt(std::stof(jsonData["avgPower"].get<std::string>()));
        }
        if (jsonData.contains("avgSpeed")) {
            workoutData.set_avgspeed(std::stof(jsonData["avgSpeed"].get<std::string>()));
        }
        if (jsonData.contains("energy")) {
            workoutData.add_calories(std::stof(jsonData["energy"].get<std::string>()));
        }
        if (jsonData.contains("secPer500")) {
            workoutData.add_secper500(std::stof(jsonData["secPer500"].get<std::string>()));
        }
        // 9、10属性未赋值
        if (jsonData.contains("elapsedTime")) {
            workoutData.set_totaltime(std::stof(jsonData["elapsedTime"].get<std::string>()));
        }
        if (jsonData.contains("activeTime")) {
            workoutData.set_activetime(std::stof(jsonData["activeTime"].get<std::string>()));
        }
        if (jsonData.contains("avgSecp500")) {
            workoutData.set_avgsecp500(std::stof(jsonData["avgSecp500"].get<std::string>()));
        }
        // 13属性未赋值
        if (jsonData.contains("energyPerHour")) {
            workoutData.add_calperhour(std::stof(jsonData["energyPerHour"].get<std::string>()));
        }
        if (jsonData.contains("output")) {
            workoutData.add_kilojoules(std::stof(jsonData["output"].get<std::string>()));
        }
        if (jsonData.contains("totalDistance")) {
            workoutData.set_totalmeters(std::stof(jsonData["totalDistance"].get<std::string>()));
        }
        if (jsonData.contains("totalOutput")) {
            workoutData.set_totaloutputs(std::stof(jsonData["totalOutput"].get<std::string>()));
        }
        // 18属性未赋值
        if (jsonData.contains("energyPerHour")) {
            workoutData.set_avgcalperhour(std::stof(jsonData["energyPerHour"].get<std::string>()));
        }
        if (jsonData.contains("totalEnergy")) {
            workoutData.set_totalcalories(std::stof(jsonData["totalEnergy"].get<std::string>()));
        }
        if (jsonData.contains("rpmTimeCount")) {
            workoutData.set_strokes(std::stof(jsonData["rpmTimeCount"].get<std::string>()));
        }
        if (jsonData.contains("HeartRate")) {
            workoutData.add_dataheartrate(std::stof(jsonData["HeartRate"].get<std::string>()));
        }
        if (jsonData.contains("avgHeartRate")) {
            workoutData.set_avgheartrate(std::stof(jsonData["avgHeartRate"].get<std::string>()));
        }
        if (jsonData.contains("maxRPM")) {
            workoutData.set_maxspm(std::stof(jsonData["maxRPM"].get<std::string>()));
        }
        if (jsonData.contains("maxSpeed")) {
            workoutData.set_maxspeed(std::stof(jsonData["maxSpeed"].get<std::string>()));
        }
        if (jsonData.contains("resistanceLevel")) {
            workoutData.add_resistance(std::stoi(jsonData["resistanceLevel"].get<std::string>()));
        }

        // 继续处理其他字段
    } catch (const std::exception &e) {
        std::cerr << "JSON parse error: " << e.what() << std::endl;
    }
}

const WorkoutData &WorkoutDataHandler::getWorkoutData() const {
    return workoutData;
}

std::string WorkoutDataHandler::serializeWorkoutDataToString() {
    std::string serializedData;
    LOGE("Starting SerializeToString");
    if (!workoutData.SerializeToString(&serializedData)) {
        LOGE("Failed to deserialize workout data.");
        std::cerr << "Failed to serialize workout data." << std::endl;
    }
    LOGE("%s", serializedData.c_str());
    LOGE("%d", serializedData.size());
    return serializedData;
}

bool WorkoutDataHandler::deserializeWorkoutDataFromString(const std::string &serializedData) {
    WorkoutData testdata;
    LOGE("Starting deserializeWorkoutDataFromString");
    if (!testdata.ParseFromString(serializedData)) {
        LOGE("failing deserializeWorkoutDataFromString");
        std::cerr << "Failed to deserialize workout data." << std::endl;
        return false;
    }
    LOGE("Starting PrintWorkoutData");
    PrintWorkoutData(testdata);
    return true;
}

void WorkoutDataHandler::PrintWorkoutData(const WorkoutData &data) {

    // 打印 repeated spm (cadence)
    std::stringstream spm_stream;
    spm_stream << "spm values:" << " ";
    for (int i = 0; i < data.spm_size(); ++i) {
        spm_stream << data.spm(i) << " ";
    }
    LOGI("%s", spm_stream.str().c_str());

    // 打印 repeated speed
    for (int i = 0; i < data.speed_size(); ++i) {
        LOGI("%f ", data.speed(i));
    }
    LOGI("\n");

    // 打印 repeated watts
    std::cout << "Watts values: ";
    for (int i = 0; i < data.watts_size(); ++i) {
        std::cout << data.watts(i) << " ";
    }
    std::cout << std::endl;

    // 打印 avgSPM
    std::cout << "Average SPM: " << data.avgspm() << std::endl;

    // 打印 repeated meters (distance)
    std::cout << "Meters values: ";
    for (int i = 0; i < data.meters_size(); ++i) {
        std::cout << data.meters(i) << " ";
    }
    std::cout << std::endl;

    // 打印 avgWatt
    std::cout << "Average Watt: " << data.avgwatt() << std::endl;

    // 打印 avgSpeed
    std::cout << "Average Speed: " << data.avgspeed() << std::endl;

    // 打印 repeated calories
    std::cout << "Calories values: ";
    for (int i = 0; i < data.calories_size(); ++i) {
        std::cout << data.calories(i) << " ";
    }
    std::cout << std::endl;

    // 打印 repeated dataTimer
    std::cout << "Data Timer values: ";
    for (int i = 0; i < data.datatimer_size(); ++i) {
        std::cout << data.datatimer(i) << " ";
    }
    std::cout << std::endl;

    // 打印 repeated secPer500
    std::cout << "Sec Per 500m values: ";
    for (int i = 0; i < data.secper500_size(); ++i) {
        std::cout << data.secper500(i) << " ";
    }
    std::cout << std::endl;

    // 打印 totalTime
    std::cout << "Total Time: " << data.totaltime() << std::endl;

    // 打印 activeTime
    std::cout << "Active Time: " << data.activetime() << std::endl;

    // 打印 avgSecp500
    std::cout << "Average Sec Per 500m: " << data.avgsecp500() << std::endl;

    // 打印 repeated calPerHour
    std::cout << "Calories Per Hour values: ";
    for (int i = 0; i < data.calperhour_size(); ++i) {
        std::cout << data.calperhour(i) << " ";
    }
    std::cout << std::endl;

    // 打印 repeated kiloJoules
    std::cout << "KiloJoules values: ";
    for (int i = 0; i < data.kilojoules_size(); ++i) {
        std::cout << data.kilojoules(i) << " ";
    }
    std::cout << std::endl;

    // 打印 totalMeters
    std::cout << "Total Meters: " << data.totalmeters() << std::endl;

    // 打印 totalOutputs
    std::cout << "Total Outputs: " << data.totaloutputs() << std::endl;

    // 打印 avgCalPerHour
    std::cout << "Average Calories Per Hour: " << data.avgcalperhour() << std::endl;

    // 打印 totalCalories
    std::cout << "Total Calories: " << data.totalcalories() << std::endl;

    // 打印 strokes
    std::cout << "Total Strokes: " << data.strokes() << std::endl;

    // 打印 repeated dataHeartRate
    std::cout << "Heart Rate values: ";
    for (int i = 0; i < data.dataheartrate_size(); ++i) {
        std::cout << data.dataheartrate(i) << " ";
    }
    std::cout << std::endl;

    // 打印 avgHeartRate
    std::cout << "Average Heart Rate: " << data.avgheartrate() << std::endl;

    // 打印 maxSpeed
    std::cout << "Max Speed: " << data.maxspeed() << std::endl;

    // 打印 maxSpm
    std::cout << "Max SPM: " << data.maxspm() << std::endl;

    // 打印 repeated resistance
    std::cout << "Resistance values: ";
    for (int i = 0; i < data.resistance_size(); ++i) {
        std::cout << data.resistance(i) << " ";
    }
    std::cout << std::endl;
}


